package com.mcb_wxc.util;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;

import com.baidu.aip.ocr.AipOcr;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.json.JSONObject;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
import org.pdfbox.util.PDFTextStripperByArea;


import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by 小生
 * 2019/2/19 9:17.
 */
public class PdfUtil {
    //生成图片的前缀
    private static final String imgPrefix = "\\ceshi_";
    //生成图片的后缀
    private static final String imgSuffix = ".png";
    /**
     * 百度云文字识别
     * @param filePath
     */
    public static String bdyTextDistinguish(String filePath) {
        final String APP_ID = "15585452";
        final String API_KEY = "oahSINuRdG8VoqoMEKiYqXNj";
        final String SECRET_KEY = "aFXVLsP5Q9wRkVz8ds1uwPUTUSdAqhK3";
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        //System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        String path = filePath;
        JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
        return res.toString(2);

    }

    /**
     * 把pdf转为图片
     * @param filePath
     * @return i ： 总共产生了多少图片
     */
    public static int onloadPdfImg(String filePath) {
        int i = 0;
        try {
            org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
              document.setFile(filePath);
              float scale = 2.5f;//缩放比例
              float rotation = 0f;//旋转角度
              for (i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage)
                        document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
                RenderedImage rendImage = image;
                try {
                    String folderPath = interceptStr(filePath, "\\");
                    File file = new File(folderPath + imgPrefix + i + imgSuffix);
                    ImageIO.write(rendImage, "png", file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                  image.flush();
              }
              document.dispose();
        }catch(Exception e){
            e.printStackTrace();
        }
        return i;
    }


    /**
     * 拆分pdf文件
     * @param filePath 要拆分文件的路径
     * @param newFilePath 新文件路径
     * @param fromPage 起始页
     * @param toPage 结束页
     */

    public static void splitPDF(String filePath,
                                String newFilePath, int fromPage, int toPage) {
        Document document = new Document();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            outputStream = new FileOutputStream(newFilePath);
            PdfReader inputPDF = new PdfReader(filePath);

            int totalPages = inputPDF.getNumberOfPages();

            //make fromPage equals to toPage if it is greater
            if(fromPage > toPage ) {
                fromPage = toPage;
            }
            if(toPage > totalPages) {
                toPage = totalPages;
            }

            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);

            document.open();
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
            PdfImportedPage page;

            while(fromPage <= toPage) {
                document.newPage();
                page = writer.getImportedPage(inputPDF, fromPage);
                cb.addTemplate(page, 0, 0);
                fromPage++;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }


    /**
     * 获取pdf的文本
     * @param filePath pdf路径
     */
    public void getPdfText (String filePath) {
        try {
            PDDocument document = PDDocument.load(new File(filePath));

            document.getClass();

            if (!document.isEncrypted()) {
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                String[] lines = pdfFileInText.split("\\r?\\n");
                for (String line : lines) {
                    System.out.println(line);
                }

            }
        } catch (Exception e) {

            e.printStackTrace();
        }

    }


    /**
     * 读取PDF文件中所有文本不包含图片，要自己处理文本格式
     * @param pdfFilePath pdf文件路径
     * @return
     */
    public static String getTextFromPDF(String pdfFilePath)
    {
        String result = null;
        FileInputStream is = null;
        PDDocument document = null;
        try {
            is = new FileInputStream(pdfFilePath);
            PDFParser parser = new PDFParser(is);
            parser.parse();
            document = parser.getPDDocument();
            PDFTextStripper stripper = new PDFTextStripper();
            result = stripper.getText(document);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 选文件
     * @param initPath 初始化盘符路径 如："E:\"
     * @return
     */
    public static String selectFilePath(String initPath) {
        //第一步选择文件
        String filePath = null;
        //可设置初始化弹的盘
        JFileChooser fileChooser = new JFileChooser(initPath);
        //FILES_AND_DIRECTORIES 标识选择文件的类型
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int returnVal = fileChooser.showOpenDialog(fileChooser);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            filePath = fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的路径
        }
        return filePath;
    }

    /**
     * 把某段字符的最后一个出现的符号以后的字符截取调 如 str:"E:\aa\ceshi.pdf" flag:"\"  结果为"E:\aa"
     * @param str
     * @param flag
     * @return
     */
    public static String interceptStr(String str, String flag) {
        int i = str.lastIndexOf(flag);
        return str.substring(0,i);
    }


    public  static void main(String[] args)
    {
        String filePath = selectFilePath("E:\\");
        if(filePath == null) {
            return;
        }
        //第一把选择的pdf表单转为图片 (测试文件再util包下)
        int imgCount = onloadPdfImg(filePath);

        //第二步识别图片的数据
        String folderPath = interceptStr(filePath, "\\");
        for(int i = 0; i < imgCount; i++) {
            String res = bdyTextDistinguish(folderPath + imgPrefix + i + imgSuffix);
            String[] arr = res.split(",");
            String nameJson = arr[2].replace("\n","").replace(" ","");
            // 转换成JSONObject对象
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(nameJson);
            Map<String,Object> datamap = jsonObject;
            String name = (String)datamap.get("words");
            name = name.replace("被考核人:","");
            System.out.println(name);

            //生成对应的pdf文件
            splitPDF(filePath,folderPath + "\\" + i + name + ".pdf",i+1,i+1);
        }
    }
}
